package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.tencent.request.TencentSendNoTeRequest;
import com.common.tencent.template.TencentNoteTemPlate;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.CodeGeneratorUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.enums.BdmBalanceChangeEnum;
import com.ruoyi.system.enums.BdmOrderEnum;
import com.ruoyi.system.mapper.BdmMemberRuleMapper;
import com.ruoyi.system.mapper.BdmUserMapper;
import com.ruoyi.system.service.IBdmBalanceChangeService;
import com.ruoyi.system.service.IBdmCloudInventoryService;
import com.ruoyi.system.service.IBdmOrderService;
import com.ruoyi.system.service.IBdmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-07
 */
@Slf4j
@Service
public class BdmUserServiceImpl extends ServiceImpl<BdmUserMapper, BdmUser> implements IBdmUserService {
    @Autowired
    private BdmUserMapper bdmUserMapper;

    @Autowired
    private IBdmOrderService iBdmOrderService;

    //云库存
    @Autowired
    private IBdmCloudInventoryService bdmCloudInventoryService;

    //订单
    @Autowired
    private IBdmOrderService bdmOrderService;
    @Autowired
    //用户 余额 积分 佣金 变动
    private IBdmBalanceChangeService bdmBalanceChangeService;

    @Autowired
    private BdmMemberRuleMapper bdmMemberRuleMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private TencentNoteTemPlate tencentNoteTemPlate;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询用户
     *
     * @param id 用户主键
     * @return 用户
     */
    @Override
    public BdmUser selectBdmUserById(Long id) {
        return bdmUserMapper.selectBdmUserById(id);
    }

    /**
     * 查询用户列表
     *
     * @param bdmUser 用户
     * @return 用户
     */
    @Override
    public List<BdmUser> selectBdmUserList(BdmUser bdmUser) {
        return bdmUserMapper.selectBdmUserList(bdmUser);
    }

    /**
     * 新增用户
     *
     * @param bdmUser 用户
     * @return 结果
     */
    @Override
    public int insertBdmUser(BdmUser bdmUser) {
        bdmUser.setCreateTime(DateUtils.getNowDate());
//        bdmUser.setPayCode(SecurityUtils.encryptPassword(bdmUser.getPayCode()));
        return bdmUserMapper.insertBdmUser(bdmUser);
    }

    /**
     * 修改用户
     *
     * @param bdmUser 用户
     * @return 结果
     */
    @Override
    public int updateBdmUser(BdmUser bdmUser) {
        bdmUser.setUpdateTime(DateUtils.getNowDate());
//        if (StringUtils.isNotBlank(bdmUser.getPayCode())){
//            bdmUser.setPayCode(SecurityUtils.encryptPassword(bdmUser.getPayCode()));
//        }
        return bdmUserMapper.updateBdmUser(bdmUser);
    }

    /**
     * 批量删除用户
     *
     * @param ids 需要删除的用户主键
     * @return 结果
     */
    @Override
    public int deleteBdmUserByIds(Long[] ids) {
        return bdmUserMapper.deleteBdmUserByIds(ids);
    }

    /**
     * 删除用户信息
     *
     * @param id 用户主键
     * @return 结果
     */
    @Override
    public int deleteBdmUserById(Long id) {
        return bdmUserMapper.deleteBdmUserById(id);
    }

    /**
     * 创建用户二维码
     *
     * @param bindUserDto
     * @return 二维码地址
     */
    @Override
    public void createUserQRCode(BindUserDto bindUserDto, HttpServletResponse response) {
        log.info("域名地址是:{}", bindUserDto.getDomain());
        String url = bindUserDto.getDomain() + "?userId=" + SecurityUtils.getUserId();
        log.info("生成二维码的userId是:{}", SecurityUtils.getUserId());
        bindUserDto.setContent(url);
        CodeGeneratorUtil.generateQrcode(bindUserDto.getContent(), bindUserDto.getWidth(), bindUserDto.getHeight(), response);
    }

    /**
     * 创建绑定用户
     * @param bindUserDto
     * @return
     */
    @Override
    @Transactional
    public int bindUser(BindUserDto bindUserDto) {
        BdmUser user = lambdaQuery().eq(BdmUser::getSysUserid, SecurityUtils.getUserId()).one();
        BdmMemberRule bdmMemberRule = bdmMemberRuleMapper.selectOne(Wrappers.<BdmMemberRule>lambdaQuery().eq(BdmMemberRule::getSysUserid, SecurityUtils.getUserId()));
        if (bdmMemberRule != null) {
            if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberLevel())) {
                throw new GlobalException("您已经是会员，请联系客服");
            }

            if (ObjectUtils.isNotEmpty(bdmMemberRule.getMemberAgencyLevel())) {
                throw new GlobalException("您已经是代理，请联系客服");
            }
        }
        int ordersCount = iBdmOrderService.lambdaQuery().eq(BdmOrder::getUserId, SecurityUtils.getUserId()).lt(BdmOrder::getOrderStatus, 5).list().size();
        if (ObjectUtils.isNotEmpty(user.getParentId()) && ordersCount > 0) {
            throw new GlobalException("已绑定关系，请联系客服");
        }
        BdmUser bdmUser = new BdmUser();
        bdmUser.setId(user.getId());
        bdmUser.setParentId(bindUserDto.getCodeUserId());
        if (bindUserDto.getCodeUserId().equals(SecurityUtils.getUserId())) {
            throw new GlobalException("绑定失败！不能绑定自己");
        }
        log.info("当前用户id是:{},待绑定的上级用户id是{}", bindUserDto.getScanUserId(), bindUserDto.getCodeUserId());
        // redisCache.setCacheObject(bindUserDto.getScanUserId().toString(), bindUserDto.getCodeUserId().toString());
        // 检测是否有购买关系
        bdmUserMapper.updateBdmUser(bdmUser);
        checkUpUser(new HashMap<String, String>(), user.getId());
        return 1;
    }

    //检测是否有闭环
    @Override
    public void checkUpUser(HashMap<String, String> voList, Long userId) {
        BdmUserVo bdmUser = baseMapper.getBdmUserByUserId(userId);
        if (ObjectUtils.isNotEmpty(voList.get(userId.toString()))) {
            throw new GlobalException("操作失败；检测到：" + userId + "有闭环");
        }
        if (bdmUser != null) {
            voList.put(userId.toString(), "1");
            if (bdmUser.getParentId() != null) {
                checkUpUser(voList, bdmUser.getParentId());
            }
        }
    }


    @Override
    public int putPaymentCode(String formerPayCode, String newPayCode) {
        BdmUser bdmUser = this.lambdaQuery().eq(BdmUser::getSysUserid, SecurityUtils.getUserId()).one();
        bdmUser.setUpdateTime(DateUtils.getNowDate());
        boolean matches = SecurityUtils.matchesPassword(formerPayCode, bdmUser.getPayCode());
        if (!matches) {
            throw new RuntimeException("旧密码不正确");
        }
        String encrypted = SecurityUtils.encryptPassword(newPayCode);
        bdmUser.setPayCode(encrypted);
        return bdmUserMapper.updateBdmUser(bdmUser);
    }

    /**
     * 查询分红池用户
     *
     * @param params
     * @return
     */
    @Override
    public List<BdmUserVo> getSvipPage(Map<String, String> params) {
        return bdmUserMapper.getSvipPage(params);
    }

    /**
     * 查询会员数据
     *
     * @param dto
     * @return
     */
    @Override
    public List<BdmMemberRuleVo> selectMemberDataPage(BdmMemberRuleDto dto) {
        return bdmUserMapper.selectMemberDataPage(dto);
    }

    /**
     * 用户团队
     *
     * @return
     */
    @Override
    public MineGroupVo userGroup(UserGroupDto userGroupDto) {
        userGroupDto.setMineUserId(SecurityUtils.getUserId());
        List<UserGroupVo> list = Optional.ofNullable(bdmUserMapper.userGroup(userGroupDto))
                .orElse(Collections.emptyList());

        MineGroupVo mineGroupVo = Optional.ofNullable(bdmUserMapper.minaCustomer(userGroupDto.getMineUserId())).orElse(new MineGroupVo());
        mineGroupVo.setWeekPerformance(mineGroupVo.getWeekPerformance().add(list.stream().map(UserGroupVo::getWeekKPI).reduce(BigDecimal.ZERO, BigDecimal::add)));
        mineGroupVo.setTotalPerformance(mineGroupVo.getTotalPerformance().add(list.stream().map(UserGroupVo::getGroupKPI).reduce(BigDecimal.ZERO, BigDecimal::add)));
        mineGroupVo.setMineGroupList(list);
        return mineGroupVo;
    }

    /**
     * 查询其他用户团队
     *
     * @param userGroupDto
     * @return
     */
    @Override
    public List<UserGroupVo> elseGroup(UserGroupDto userGroupDto) {
        userGroupDto.setSysUserid(SecurityUtils.getUserId());
        return Optional.ofNullable(bdmUserMapper.userGroup(userGroupDto))
                .orElse(Collections.emptyList()).stream().peek(vo -> {
                    vo.setUserNumber(new BigDecimal(vo.getUserOneLevelNumber()).add(new BigDecimal(vo.getUserTwoLevelNumber())).toString());
                }).collect(Collectors.toList());
    }

    /**
     * 团队人数
     *
     * @param dto
     * @return
     */
    @Override
    public List<BdmUserTeamVo> getTeamNumber(BdmUserTeamDto dto) {
        List<Long> orderList = new ArrayList<>();
        orderList.add(BdmOrderEnum.CHARGEBACK.getType());
        orderList.add(BdmOrderEnum.CLOSE.getType());
        // 获取当前时间（带时区）
        ZoneId zone = ZoneId.of("Asia/Shanghai");
        LocalDateTime now = LocalDateTime.now(zone);

        // 计算本周范围（周一00:00 ~ 周日23:59:59）
        LocalDateTime weekStart = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
                .truncatedTo(ChronoUnit.DAYS);
        LocalDateTime weekEnd = weekStart.plusDays(6)
                .with(LocalTime.MAX);
        List<BdmUserTeamVo> list = baseMapper.getTeamNumber(dto);
        list.stream().peek(item -> {
            // 获取本人团队的用户id
            List<Long> userIds = baseMapper.getSelfTeamCount(item.getUserId());
            userIds.add(item.getUserId());
            item.setTeamCount(userIds.size());
            List<BdmOrder> bdmOrders = iBdmOrderService.lambdaQuery().in(BdmOrder::getUserId, userIds).notIn(BdmOrder::getOrderStatus, orderList).list();
            item.setTeamOrderNumber(bdmOrders.size());
            item.setTeamPerformance(bdmOrders.stream().map(BdmOrder::getPayMoney).map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add));
            // 本周业绩
            item.setThisWeekPerformance(bdmOrders.stream()
                    .filter(order -> {
                        Date date = order.getCreateTime();
                        // 转换为 LocalDateTime
                        Instant instant = date.toInstant();
                        LocalDateTime orderTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
                        return !orderTime.isBefore(weekStart) &&
                                !orderTime.isAfter(weekEnd);
                    }).map(BdmOrder::getPayMoney).map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add));

        }).collect(Collectors.toList());
        return list;

    }

    /**
     * 团队人数列表 团队业绩
     *
     * @param dto
     * @return
     */
    @Override
    public List<BdmOrderVo> getTeamPerformance(BdmUserTeamDto dto) {
        return baseMapper.getTeamPerformance(dto);
    }

    /**
     * 云库存增加余额 减少佣金
     */
    @Override
    public void cloudInventoryIncreasesTheBalance(BdmCloudInventoryItem bdmCloudInventoryItem) {
        Long userId = bdmCloudInventoryItem.getUserId();
        BdmUser bdmUser = this.lambdaQuery().eq(BdmUser::getSysUserid, userId).one();
        ArrayList<BdmBalanceChange> bdmBalanceChanges = new ArrayList<>();
        //如果没有订单 就从下级云库存进价获取金额
        if (StringUtils.isEmpty(bdmCloudInventoryItem.getRelevantDocumentId())) {
            //下级的云库存
            BdmCloudInventory bdmCloudInventory = bdmCloudInventoryService.lambdaQuery()
                    .eq(BdmCloudInventory::getUserId, bdmCloudInventoryItem.getCorrelationUserId())
                    .eq(BdmCloudInventory::getGoodId, bdmCloudInventoryItem.getGoodId())
                    .one();

            BigDecimal multiply = bdmCloudInventory.getStockPrice().multiply(new BigDecimal(bdmCloudInventoryItem.getNum()));


            //插入余额收益积分变动表
            BdmBalanceChange bdmBalanceChange = BdmBalanceChange.getBdmBalanceChange(
                    userId,
                    null,
                    multiply.toString(),
                    bdmUser.getRemainingSum().toString(),
                    bdmUser.getRemainingSum().add(multiply).toString(),
                    Long.parseLong(BdmBalanceChangeEnum.BALANCE.getType()),
                    Long.parseLong(BdmBalanceChangeEnum.ADD.getType()),
                    BdmBalanceChangeEnum.LOWER_LEVEL_PURCHASES_OF_CLOUD_INVENTORY_ITEMS.getDescription()
            );
            //插入余额收益积分变动表
            BdmBalanceChange bdmBalanceChange1 = BdmBalanceChange.getBdmBalanceChange(
                    userId,
                    null,
                    multiply.toString(),
                    bdmUser.getEarnings().toString(),
                    bdmUser.getEarnings().add(multiply).toString(),
                    Long.parseLong(BdmBalanceChangeEnum.BROKERAGE.getType()),
                    Long.parseLong(BdmBalanceChangeEnum.SUBTRACT.getType()),
                    BdmBalanceChangeEnum.DEDUCTION_WITHDRAW_DEPOSIT.getDescription()
            );

            //增加余额减少佣金
            bdmUser.setRemainingSum(bdmUser.getRemainingSum().add(multiply));
            bdmUser.setEarnings(bdmUser.getEarnings().subtract(multiply));
            bdmBalanceChanges.add(bdmBalanceChange);
            bdmBalanceChanges.add(bdmBalanceChange1);

        } else {
            //直接从订单中获取
            BdmOrder bdmOrder = bdmOrderService.lambdaQuery()
                    .eq(BdmOrder::getId, bdmCloudInventoryItem.getRelevantDocumentId()).one();

            BigDecimal subtract = new BigDecimal(bdmOrder.getPayMoney()).subtract(new BigDecimal(bdmOrder.getDeliveryCost()));


            //插入余额收益积分变动表
            BdmBalanceChange bdmBalanceChange = BdmBalanceChange.getBdmBalanceChange(
                    userId,
                    null,
                    subtract.toString(),
                    bdmUser.getRemainingSum().toString(),
                    bdmUser.getRemainingSum().add(subtract).toString(),
                    Long.parseLong(BdmBalanceChangeEnum.BALANCE.getType()),
                    Long.parseLong(BdmBalanceChangeEnum.ADD.getType()),
                    BdmBalanceChangeEnum.LOWER_LEVEL_PURCHASES_OF_CLOUD_INVENTORY_ITEMS.getDescription()
            );
            //插入余额收益积分变动表
            BdmBalanceChange bdmBalanceChange1 = BdmBalanceChange.getBdmBalanceChange(
                    userId,
                    null,
                    subtract.toString(),
                    bdmUser.getEarnings().toString(),
                    bdmUser.getEarnings().add(subtract).toString(),
                    Long.parseLong(BdmBalanceChangeEnum.BROKERAGE.getType()),
                    Long.parseLong(BdmBalanceChangeEnum.SUBTRACT.getType()),
                    BdmBalanceChangeEnum.DEDUCTION_WITHDRAW_DEPOSIT.getDescription()
            );

            bdmBalanceChanges.add(bdmBalanceChange);
            bdmBalanceChanges.add(bdmBalanceChange1);
            //增加余额 减少收益
            bdmUser.setRemainingSum(bdmUser.getRemainingSum().add(subtract));
            bdmUser.setEarnings(bdmUser.getEarnings().subtract(subtract));

        }
        //插入余额收益积分变动表
        bdmBalanceChangeService.saveBatch(bdmBalanceChanges);
        this.saveOrUpdate(bdmUser);
    }

    /**
     * 获取短信验证码
     *
     * @return
     */
    @Override
    public void getNoteCode() {
        Long userId = SecurityUtils.getUserId();
        BdmUserVo bdmUserVo = baseMapper.getBdmUserByUserId(userId);
        if (bdmUserVo == null || StringUtils.isBlank(bdmUserVo.getPhonenumber())) {
            throw new RuntimeException("当前登录账号暂未获取到相关手机号");
        }

        String phoneNumber = bdmUserVo.getPhonenumber();
        long second = System.currentTimeMillis() / 1000;
        String caCheCode = stringRedisTemplate.opsForValue().get(CacheConstants.NOTE_CODE + phoneNumber);
        if (!StringUtils.isBlank(caCheCode)) {
            String caCheSecond = caCheCode.split("_")[1];
            if ((second - Long.parseLong(caCheSecond)) <= 300) {
                throw new RuntimeException("验证码五分钟内请勿重复发送");
            }
        }

        String code = new Random().nextInt(9000) + 1000 + "";
        TencentSendNoTeRequest request = new TencentSendNoTeRequest();
        String[] phone = {"+86" + phoneNumber};
        request.setPhoneNumberSet(phone);
        request.setSignName("武汉本维美贸易");
        request.setTemplateId("2367631");
        String[] param = {code};
        request.setTemplateParamSet(param);
        request.setSmsSdkAppId("1400958886");
        tencentNoteTemPlate.sendTencentNote(request);
        stringRedisTemplate.opsForValue().set(CacheConstants.NOTE_CODE + phoneNumber, code + "_" + second, 5, TimeUnit.MINUTES);
    }

    /**
     * 修改支付密码
     *
     * @param dto
     */
    @Override
    public void updatePayPassword(BdmUserDto dto) {
        Long userId = SecurityUtils.getUserId();
        BdmUserVo bdmUserVo = baseMapper.getBdmUserByUserId(userId);
        if (bdmUserVo == null || StringUtils.isBlank(bdmUserVo.getPhonenumber())) {
            throw new RuntimeException("当前登录账号暂未获取到相关手机号");
        }
        String phoneNumber = bdmUserVo.getPhonenumber();
        String cacheCode = stringRedisTemplate.opsForValue().get(CacheConstants.NOTE_CODE + phoneNumber);
        if (StringUtils.isBlank(cacheCode)) {
            throw new RuntimeException("验证码不存在");
        }
        String[] code = cacheCode.split("_");
        if (!dto.getCode().equalsIgnoreCase(code[0].split(",")[0])) {
            throw new RuntimeException("验证码不匹配");
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password = encoder.encode(dto.getNewPayPassword());
        lambdaUpdate().eq(BdmUser::getSysUserid, userId).set(BdmUser::getPayCode, password).update();
        stringRedisTemplate.delete(CacheConstants.NOTE_CODE + phoneNumber);
    }

    @Override
    public void updateBdmUserMoney(Long sysUserid, BigDecimal amount) {
        baseMapper.updateBdmUserMoney(sysUserid, amount);
    }

    @Override
    public void updateUserMone(Long sysUserid, BigDecimal topupAmount) {
        baseMapper.updateUserMone(sysUserid, topupAmount);
    }


    @Override
    public AjaxResult findUserTeam(BdmUserTeamDto dto) {
        Integer pageNum1 = dto.getPageNum();
        Integer pageSize1 = dto.getPageSize();
        dto.setPageNum(null);
        dto.setPageSize(null);

        String nikeNameOrPhoneNumber = dto.getNikeNameOrPhoneNumber();
        if (nikeNameOrPhoneNumber != null && nikeNameOrPhoneNumber.matches("\\d+")) {
            dto.setFindId(Long.parseLong(nikeNameOrPhoneNumber));
        }

        // 查询用户团队（包含下级信息）
        List<BdmUserVo> list = baseMapper.selectUserTeamWithDetail(dto);

        Long selfId = dto.getUserId();
        List<BdmUserVo> levelOne = list.stream()
                .filter(vo -> selfId.equals(vo.getParentId()))
                .collect(Collectors.toList());

        List<BdmUserVo> levelTwo = list.stream()
                .filter(vo -> !selfId.equals(vo.getParentId()) &&
                        levelOne.stream().anyMatch(p -> p.getSysUserid().equals(vo.getParentId())))
                .collect(Collectors.toList());

        // ⭐ 根据 isOne 判断是直推还是间推
        List<BdmUserVo> targetList;
        if (dto.getIsOne() != null && dto.getIsOne() == 1) {
            targetList = levelTwo; // 间推
        } else {
            targetList = levelOne; // 直推
        }

        // 特殊搜索条件
        if (dto.getFindId() != null
                || (dto.getJoinDate() != null && !dto.getJoinDate().isEmpty())
                || dto.getUserMemberLevel() != null) {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            targetList = targetList.stream()
                    .filter(vo -> {
                        // findId 条件
                        boolean matchFindId = dto.getFindId() == null || vo.getSysUserid().equals(dto.getFindId());

                        // joinDate 条件
                        boolean matchJoinDate = true;
                        if (dto.getJoinDate() != null && !dto.getJoinDate().isEmpty() && vo.getCreateTime() != null) {
                            String createDateStr = sdf.format(vo.getCreateTime()); // 格式化成 yyyy-MM-dd
                            matchJoinDate = dto.getJoinDate().equals(createDateStr);
                        }

                        // userMemberLevel 匹配 level 或 vipLevel
                        boolean matchUserLevel = true;
                        if (dto.getUserMemberLevel() != null) {
                            matchUserLevel =
                                    (vo.getLevel() != null && vo.getLevel().equals(dto.getUserMemberLevel()))
                                            || (vo.getVipLevel() != null && vo.getVipLevel().equals(dto.getUserMemberLevel()));
                        }

                        return matchFindId && matchJoinDate && matchUserLevel;
                    })
                    .collect(Collectors.toList());
        }
        // ⭐ 计算每个用户的下级人数
        for (BdmUserVo vo : targetList) {
            int subordinateNum = (int) list.stream()
                    .filter(u -> vo.getSysUserid().equals(u.getParentId()))
                    .count();
            vo.setSubordinateNum(subordinateNum);
        }

        // 查询上级信息
        BdmUserVo bdmUserVo = baseMapper.selectUserParentDetail(dto);

        // 分页处理（只对当前 targetList 分页）
        int total = targetList.size();
        int pageNum = pageNum1 == null ? 1 : pageNum1;
        int pageSize = pageSize1 == null ? 10 : pageSize1;
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);
        List<BdmUserVo> pagedList = fromIndex < total ? targetList.subList(fromIndex, toIndex) : new ArrayList<>();

        // 封装返回对象
        BdmUserTeamLayer teamLayer = new BdmUserTeamLayer();
        teamLayer.setBdmUserVo(bdmUserVo);
        if (dto.getIsOne() != null && dto.getIsOne() == 1) {
            teamLayer.setBdmUserTwoVoList(pagedList);   // 只返回二级
        } else {
            teamLayer.setBdmUserVoList(pagedList);      // 只返回一级
        }

        return AjaxResult.success()
                .put("total", total)
                .put("pageNum", pageNum)
                .put("pageSize", pageSize)
                .put("rows", teamLayer);
    }

    @Override
    public AjaxResult getUserSuperior(BdmUserTeamDto dto) {
        BdmUserVo bdmUserVo = baseMapper.selectUserByUserId(dto.getUserId());
        if (bdmUserVo != null && bdmUserVo.getParentId() != null) {
            BdmUserVo bdmUser1 = baseMapper.selectUserByUserId(bdmUserVo.getParentId());
            return AjaxResult.success(bdmUser1);
        } else {
            return AjaxResult.success("");
        }
    }

    /**
     * 修改分红池用户分红状态
     *
     * @param sysUserId
     * @return
     */
    @Override
    public AjaxResult updateBonusStatus(Long sysUserId, Integer bonusStatus) {
        if (bonusStatus == null) {
            return AjaxResult.success(baseMapper.updateBonusStatusIsNull(sysUserId));
        } else {
            return AjaxResult.success(baseMapper.updateBonusStatus(sysUserId));
        }
    }


}
